package base.netall;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;

public class GetPage {

	public static final int TIME_OUT = 10 * 1000;

	public static void main(String[] args) throws Exception {

		 String url = "http://www.baidu.com";
		 throwUrl(url);

//		String host = "www.baidu.com";
//		int port = 80;
//		socketUrl(host, port);
	}
	
	public static void httpUrl(String u)throws Exception{
		
	}

	/**
	 * 通过url直接获取该页面的内容
	 * 
	 * @param u
	 * @throws Exception
	 */
	public static void throwUrl(String u) throws Exception {
		URL url = new URL(u);
		InputStream stream ;
//		stream=url.openStream();
		URLConnection connection = url.openConnection();
		connection.connect();
		connection.setConnectTimeout(TIME_OUT);
		stream=connection.getInputStream();
		
		print(stream, "gb2312");
	}
	
	/**
	 * 通过socket连接获取页面内容
	 */
	public static void socketUrl(String host, int port) throws Exception {
		
		InetAddress address=InetAddress.getByName(host);
		
		Socket socket = new Socket(address, port);
		
		BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
        wr.write("GET " + "/" + " HTTP/1.0\r\n");
        wr.write("HOST:" + host + "\r\n");
        wr.write("Accept:*/*\r\n");
        wr.write("\r\n");
        wr.flush();

		socket.setSoTimeout(TIME_OUT);
		InputStream stream = socket.getInputStream();
		print(stream, "gb2312");
	}

	/**
	 * 将stream打印出来
	 * @param stream
	 * @param charset
	 * @throws Exception
	 */
	public static void print(InputStream stream, String charset)
			throws Exception {

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				stream, charset));

		String cont;
		while ((cont = reader.readLine()) != null) {
			System.out.print(cont);
		}
		System.out.println();
	}
}
